﻿using System;
using System.Web;
using System.Web.SessionState;
using System.Web.Security;

using iSun.Common;

using iSun.BLL;
using iSun.Entity;

namespace iSun.Web.UI.Controls
{
    /// <summary>
    /// 系统LOGON请求
    /// </summary>
    public class LogOn : BaseHandler, IHttpHandler, IRequiresSessionState 
    {
        public bool IsReusable
        {
            // Return false in case your Managed Handler cannot be reused for another request.
            // Usually this would be false in case you have some state information preserved per request.
            get { return true; }
        }

        /// <summary>
        /// You will need to configure this handler in the web.config file of your 
        /// web and register it with IIS before being able to use it. For more information
        /// see the following link: http://go.microsoft.com/?linkid=8101007
        /// </summary>
        public void ProcessRequest(HttpContext context)
        {
            string UserName = context.Request["UserName"].ToLower();
            string Password = context.Request["Password"].ToString();
            BUser buser = new BUser();
            DatUser user = new DatUser();
            int i =  buser.Login(UserName, Password,out user);
            if (i == -1)
            {
                context.Session["User"]=user;
                FormsAuthentication.SetAuthCookie(UserName, true);
                context.Response.Cookies[FormsAuthentication.FormsCookieName].Expires = DateTime.Now.AddHours(8); 

                FormsAuthenticationTicket authTicket = new FormsAuthenticationTicket(1,UserName, // 与身份验证票关联的用户名。 
                                                        DateTime.Now, // Cookie 的发出时间。 
                                                        DateTime.Now.AddMinutes(20),// Cookie 的到期日期。 
                                                        false // 如果 Cookie 是持久的，为 true；否则为 false
                                                        ,user.ToJSON());
                string encryptedTicket = FormsAuthentication.Encrypt(authTicket);
  
                HttpCookie cookie = new HttpCookie("UserName");
                cookie.Name = UserName+"_01";
                cookie.Value = encryptedTicket;
                cookie.Expires = DateTime.Now.AddHours(8);
                context.Response.Cookies.Add(cookie);
            }
            context.Response.Write(i.ToString());
        }
    }
}
